﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class DBHelper
    {
        private static SqlConnection conn;
        private static SqlDataAdapter sda;
        private static SqlCommand comm;
        public static string connstr = "Server=rm-bp13x228e5ip7ogsyzo.sqlserver.rds.aliyuncs.com,3433;uid=student;pwd=abc123!@#;database =Team4_DDBookDB";
        private static void InitConn()
        {
            if (conn == null)
            {
                conn = new SqlConnection(connstr);
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
        }

        /// <summary>
        /// 执行查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(String sql)
        {
            InitConn();
            sda = new SqlDataAdapter(sql, conn);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            return dt;
        }
        public static int GetCount(String sql)
        {
            int count = 0;
            using (SqlConnection connStr = new SqlConnection(connstr))
            {
                connStr.Open();
                using (SqlCommand cmd = connStr.CreateCommand())
                {
                    cmd.CommandText = sql;
                    count = Convert.ToInt32(cmd.ExecuteScalar());
                }
            }
            return count;
        }
        /// <summary>
        /// 执行增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool Execute(String sql)
        {
            InitConn();
            comm = new SqlCommand(sql, conn);
            int result = comm.ExecuteNonQuery();
            conn.Close();
            return result > 0;
        }
    }
}
